<?php
/******************************
 * EQdkp
 * Copyright 2002-2003
 * Licensed under the GNU GPL.  See COPYING for full terms.
 * ------------------
 * manage_users.php
 * Began: Sun December 29 2002
 *
 * $Id: manage_users.php 541 2008-05-20 06:56:16Z rspeicher $
 *
 ******************************/

define('EQDKP_INC', true);
define('IN_ADMIN', true);
$eqdkp_root_path = './../';
include_once($eqdkp_root_path . 'common.php');

$fv = new Form_Validate;

// Start session management
$user->start();
$user->setup();
$user->check_auth('a_users_man');

if ( isset($_POST['submit']) )
{
    $action = 'update';
    
    // See if the user exists
    $sql = 'SELECT au.*, u.*
            FROM ' . USERS_TABLE . ' u 
            LEFT JOIN ' . AUTH_USERS_TABLE . " au
            ON (u.user_id = au.user_id)
            WHERE u.username='".$_REQUEST[URI_NAME]."'";
    $result = $db->query($sql);
    if ( !$user_data = $db->fetch_record($result) )
    {
        message_die($user->lang['error_user_not_found']);
    }
    $db->free_result($result);

    // Error-check the form
    $change_username = false;
    if ( $_POST['username'] != $_POST[URI_NAME] )
    {
        // They changed the username, see if it's already registered
        $sql = 'SELECT user_id
                FROM ' . USERS_TABLE . "
                WHERE username='".$_POST['username']."'";
        if ( $db->num_rows($db->query($sql)) > 0 )
        {
            $fv->errors['username'] = $user->lang['username_already_registered'];
        }
        $change_username = true;
    }
    $change_password = false;
    if ( (!empty($_POST['new_user_password1'])) || (!empty($_POST['new_user_password2'])) )
    {
        $fv->matching_passwords('new_user_password1', 'new_user_password2', $user->lang['fv_match_password']);
        $change_password = true;
    }
    $fv->is_number(array(
        'user_alimit' => $user->lang['fv_number'],
        'user_elimit' => $user->lang['fv_number'],
        'user_ilimit' => $user->lang['fv_number'],
        'user_nlimit' => $user->lang['fv_number'],
        'user_rlimit' => $user->lang['fv_number'])
    );
    
    if ( $fv->is_error() )
    {
        $action = 'settings';
    }
}
// Figure out what submit button was pressed
elseif ( isset($_GET[URI_NAME]) )
{
    // See if the user exists
    $sql = 'SELECT au.*, u.*
            FROM ' . USERS_TABLE . ' u
            LEFT JOIN ' . AUTH_USERS_TABLE . " au
            ON (u.user_id = au.user_id)
            WHERE u.username='".$_GET[URI_NAME]."'";
    $result = $db->query($sql);
    if ( !$user_data = $db->fetch_record($result) )
    {
        message_die($user->lang['error_user_not_found']);
    }
    $db->free_result($result);
    
    $action = 'settings';
}
else
{
    $action = 'display';
}

switch ( $action )
{
    //
    // Process the update
    //
    case 'update':
        $_POST = htmlspecialchars_array($_POST);
        
        $user_id = $user_data['user_id'];
        
        // Errors have been checked at this point, build the query
        // User settings
        $sql = 'UPDATE ' . USERS_TABLE . "
                SET";
        if ( $change_username )
        {
            $sql .= " username='".$_POST['username']."', ";
        }
        if ( $change_password )
        {
            $sql .= " user_password='".md5($_POST['new_user_password1'])."', ";
        }
        $sql .= " user_email='".$_POST['user_email']."', ";
        
        $sql .= " user_alimit='".$_POST['user_alimit']."', user_elimit='".$_POST['user_elimit']."', user_ilimit='".$_POST['user_ilimit']."',
                  user_nlimit='".$_POST['user_nlimit']."', user_rlimit='".$_POST['user_rlimit']."', ";
                  
        $sql .= " user_lang='".$_POST['user_lang']."', user_style='".$_POST['user_style']."', 
                  user_active='".$_POST['user_active']."'";
                  
        $sql .= " WHERE user_id='".$user_data['user_id']."'";
        
        if ( !($result = $db->query($sql)) )
        {
            message_die('Could not update user information', '', __FILE__, __LINE__, $sql);
        }
        
        // Permissions
        $sql = 'SELECT auth_id, auth_value
                FROM ' . AUTH_OPTIONS_TABLE . '
                ORDER BY auth_id';
        $result = $db->query($sql);
        while ( $row = $db->fetch_record($result) )
        {
            update_auth_users($row['auth_id'], ( isset($_POST[$row['auth_value']]) ) ? 'Y' : 'N');
        }
        
        message_die($user->lang['update_settings_success']);
        
        break;
    
    //
    // Display the settings form
    //
    case 'settings':
        $user_id = $user_data['user_id'];
        
        $tpl->assign_vars(array(
            'F_SETTINGS' => 'manage_users.php'.$SID,
            
            'S_CURRENT_PASSWORD' => false,
            'S_NEW_PASSWORD' => true,
            'S_SETTING_ADMIN' => true,
            'NAME' => $_REQUEST[URI_NAME],

            'L_REGISTRATION_INFORMATION' => $user->lang['registration_information'],
            'L_REQUIRED_FIELD_NOTE' => $user->lang['required_field_note'],
            'L_USERNAME' => $user->lang['username'],
            'L_EMAIL_ADDRESS' => $user->lang['email_address'],
            'L_NEW_PASSWORD' => $user->lang['new_password'],
            'L_NEW_PASSWORD_NOTE' => $user->lang['new_password_note'],
            'L_CONFIRM_PASSWORD' => $user->lang['confirm_password'],
            'L_CONFIRM_PASSWORD_NOTE' => $user->lang['confirm_password_note'],
            'L_PREFERENCES' => $user->lang['preferences'],
            'L_ADJUSTMENTS_PER_PAGE' => $user->lang['adjustments_per_page'],
            'L_EVENTS_PER_PAGE' => $user->lang['events_per_page'],
            'L_ITEMS_PER_PAGE' => $user->lang['items_per_page'],
            'L_NEWS_PER_PAGE' => $user->lang['news_per_page'],
            'L_RAIDS_PER_PAGE' => $user->lang['raids_per_page'],
            'L_LANGUAGE' => $user->lang['language'],
            'L_STYLE' => $user->lang['style'],
            'L_PREVIEW' => $user->lang['preview'],
            'L_PERMISSIONS' => $user->lang['permissions'],
            'L_S_ADMIN_NOTE' => $user->lang['s_admin_note'],
            'L_ACCOUNT_ENABLED' => $user->lang['account_enabled'],
            'L_YES' => $user->lang['yes'],
            'L_NO' => $user->lang['no'],
            'L_MANAGE' => $user->lang['manage'],
            'L_CONFIGURATION' => $user->lang['configuration'],
            'L_PLUGINS' => $user->lang['plugins'],
            'L_STYLES' => $user->lang['styles'],
            'L_USERS' => $user->lang['users'],
            'L_MEMBERS' => $user->lang['members'],
            'L_LOGS' => $user->lang['logs'],
            'L_LIST' => $user->lang['list'],
            'L_VIEW' => $user->lang['view'],
            'L_ADD' => $user->lang['add'],
            'L_UPDATE' => $user->lang['update'],
            'L_DELETE' => $user->lang['delete'],
            'L_EVENTS' => $user->lang['events'],
            'L_GROUP_ADJUSTMENTS' => $user->lang['group_adjustments'],
            'L_INDIVIDUAL_ADJUSTMENTS' => $user->lang['individual_adjustments'],
            'L_ITEMS' => $user->lang['items'],
            'L_NEWS' => $user->lang['news'],
            'L_RAIDS' => $user->lang['raids'],
            'L_TURN_INS' => $user->lang['turn_ins'],
            'L_SUBMIT' => $user->lang['submit'],
            'L_RESET' => $user->lang['reset'],

            'USERNAME' => $user_data['username'],
            'USER_EMAIL' => $user_data['user_email'],
            'USER_ALIMIT' => $user_data['user_alimit'],
            'USER_ELIMIT' => $user_data['user_elimit'],
            'USER_ILIMIT' => $user_data['user_ilimit'],
            'USER_NLIMIT' => $user_data['user_nlimit'],
            'USER_RLIMIT' => $user_data['user_rlimit'],
            'USER_ACTIVE_YES_CHECKED' => ( $user_data['user_active'] == '1' ) ? ' checked="checked"' : '',
            'USER_ACTIVE_NO_CHECKED' => ( $user_data['user_active'] == '0' ) ? ' checked="checked"' : '',

            'EVENT_ADD_CHECKED' => ( $user->check_auth('a_event_add', false, $user_id) ) ? ' checked="checked"' : '',
            'EVENT_UPD_CHECKED' => ( $user->check_auth('a_event_upd', false, $user_id) ) ? ' checked="checked"' : '',
            'EVENT_DEL_CHECKED' => ( $user->check_auth('a_event_del', false, $user_id) ) ? ' checked="checked"' : '',
            'EVENT_LIST_CHECKED' => ( $user->check_auth('u_event_list', false, $user_id) ) ? ' checked="checked"' : '',
            'EVENT_VIEW_CHECKED' => ( $user->check_auth('u_event_view', false, $user_id) ) ? ' checked="checked"' : '',
            
            'GROUPADJ_ADD_CHECKED' => ( $user->check_auth('a_groupadj_add', false, $user_id) ) ? ' checked="checked"' : '',
            'GROUPADJ_UPD_CHECKED' => ( $user->check_auth('a_groupadj_upd', false, $user_id) ) ? ' checked="checked"' : '',
            'GROUPADJ_DEL_CHECKED' => ( $user->check_auth('a_groupadj_del', false, $user_id) ) ? ' checked="checked"' : '',
            
            'INDIVADJ_ADD_CHECKED' => ( $user->check_auth('a_indivadj_add', false, $user_id) ) ? ' checked="checked"' : '',
            'INDIVADJ_UPD_CHECKED' => ( $user->check_auth('a_indivadj_upd', false, $user_id) ) ? ' checked="checked"' : '',
            'INDIVADJ_DEL_CHECKED' => ( $user->check_auth('a_indivadj_del', false, $user_id) ) ? ' checked="checked"' : '',
            
            'ITEM_ADD_CHECKED' => ( $user->check_auth('a_item_add', false, $user_id) ) ? ' checked="checked"' : '',
            'ITEM_UPD_CHECKED' => ( $user->check_auth('a_item_upd', false, $user_id) ) ? ' checked="checked"' : '',
            'ITEM_DEL_CHECKED' => ( $user->check_auth('a_item_del', false, $user_id) ) ? ' checked="checked"' : '',
            'ITEM_LIST_CHECKED' => ( $user->check_auth('u_item_list', false, $user_id) ) ? ' checked="checked"' : '',
            'ITEM_VIEW_CHECKED' => ( $user->check_auth('u_item_view', false, $user_id) ) ? ' checked="checked"' : '',
            
            'NEWS_ADD_CHECKED' => ( $user->check_auth('a_news_add', false, $user_id) ) ? ' checked="checked"' : '',
            'NEWS_UPD_CHECKED' => ( $user->check_auth('a_news_upd', false, $user_id) ) ? ' checked="checked"' : '',
            'NEWS_DEL_CHECKED' => ( $user->check_auth('a_news_del', false, $user_id) ) ? ' checked="checked"' : '',
            
            'RAID_ADD_CHECKED' => ( $user->check_auth('a_raid_add', false, $user_id) ) ? ' checked="checked"' : '',
            'RAID_UPD_CHECKED' => ( $user->check_auth('a_raid_upd', false, $user_id) ) ? ' checked="checked"' : '',
            'RAID_DEL_CHECKED' => ( $user->check_auth('a_raid_del', false, $user_id) ) ? ' checked="checked"' : '',
            'RAID_LIST_CHECKED' => ( $user->check_auth('u_raid_list', false, $user_id) ) ? ' checked="checked"' : '',
            'RAID_VIEW_CHECKED' => ( $user->check_auth('u_raid_view', false, $user_id) ) ? ' checked="checked"' : '',

            'TURNIN_ADD_CHECKED' => ( $user->check_auth('a_turnin_add', false, $user_id) ) ? ' checked="checked"' : '',
            
            'MEMBERS_MAN_CHECKED' => ( $user->check_auth('a_members_man', false, $user_id) ) ? ' checked="checked"' : '',
            'MEMBER_LIST_CHECKED' => ( $user->check_auth('u_member_list', false, $user_id) ) ? ' checked="checked"' : '',
            'MEMBER_VIEW_CHECKED' => ( $user->check_auth('u_member_view', false, $user_id) ) ? ' checked="checked"' : '',
            
            'CONFIG_MAN_CHECKED' => ( $user->check_auth('a_config_man', false, $user_id) ) ? ' checked="checked"' : '',
            'PLUGINS_MAN_CHECKED' => ( $user->check_auth('a_plugins_man', false, $user_id) ) ? ' checked="checked"' : '',
            'STYLES_MAN_CHECKED' => ( $user->check_auth('a_styles_man', false, $user_id) ) ? ' checked="checked"' : '',
            'USERS_MAN_CHECKED' => ( $user->check_auth('a_users_man', false, $user_id) ) ? ' checked="checked"' : '',
            'LOGS_VIEW_CHECKED' => ( $user->check_auth('a_logs_view', false, $user_id) ) ? ' checked="checked"' : '',
            
            'FV_USERNAME' => $fv->generate_error('username'),
            'FV_NEW_PASSWORD' => $fv->generate_error('new_user_password1'),
            'FV_USER_ALIMIT' => $fv->generate_error('user_alimit'),
            'FV_USER_ELIMIT' => $fv->generate_error('user_elimit'),
            'FV_USER_ILIMIT' => $fv->generate_error('user_ilimit'),
            'FV_USER_NLIMIT' => $fv->generate_error('user_nlimit'),
            'FV_USER_RLIMIT' => $fv->generate_error('user_rlimit'))
        );
        
        // Plugin permissions
        $plugin_permissions = '';
        do_hook('user_permissions', $plugin_permissions);
        $tpl->assign_vars(array(
            'PLUGIN_PERMISSIONS' => trim($plugin_permissions))
        );

        if ( $dir = @opendir($eqdkp_root_path . 'language/') )
        {
            while ( $file = @readdir($dir) )
            {
                if ( (!is_file($eqdkp_root_path . 'language/' . $file)) && (!is_link($eqdkp_root_path . 'language/' . $file)) && ($file != '.') && ($file != '..') && ($file != 'CVS') )
                {
                    $tpl->assign_block_vars('lang_row', array(
                        'VALUE' => $file,
                        'SELECTED' => ( $user_data['user_lang'] == $file ) ? ' selected="selected"' : '',
                        'OPTION' => ucfirst($file))
                    );
                }
            }
        }

        $sql = 'SELECT style_id, style_name
                FROM ' . STYLES_TABLE . '
                ORDER BY style_name';
        $result = $db->query($sql);
        while ( $row = $db->fetch_record($result) )
        {
            $tpl->assign_block_vars('style_row', array(
                'VALUE' => $row['style_id'],
                'SELECTED' => ( $user_data['user_style'] == $row['style_id'] ) ? ' selected="selected"' : '',
                'OPTION' => $row['style_name'])
            );
        }
        $db->free_result($result);

        $page_title = sprintf($user->lang['title_prefix'], $eqdkp->config['guildtag'], $eqdkp->config['dkp_name']).': ';
        include_once($eqdkp_root_path . 'includes/page_header.php');
        
        $tpl->set_filenames(array(
            'body' => 'settings.html')
        );
        
        include_once($eqdkp_root_path . 'includes/page_tail.php');

        break;

    //
    // Display the list of members
    //
    case 'display':
        $sort_order = array(
            0 => array('u.username', 'u.username desc'),
            1 => array('u.user_email', 'u.user_email desc'),
            2 => array('u.user_lastvisit desc', 'u.user_lastvisit'),
            3 => array('u.user_active desc', 'u.user_active'),
            4 => array('s.session_id desc', 's.session_id')
        );
        
        $current_order = switch_order($sort_order);
        
        $total_users = $db->query_first('SELECT count(*) FROM ' . USERS_TABLE);
        $start = ( isset($_GET['start']) ) ? $_GET['start'] : 0;
        
        $sql = 'SELECT u.user_id, u.username, u.user_email, u.user_lastvisit, u.user_active, s.session_id
                FROM ( ' . USERS_TABLE . ' u
                LEFT JOIN ' . SESSIONS_TABLE . ' s
                ON u.user_id = s.session_user_id )
                GROUP BY u.username
                ORDER BY ' . $current_order['sql'] . '
                LIMIT '.$start.',100';
        if ( !($users_result = $db->query($sql)) )
        {
            message_die('Could not obtain user information', '', __FILE__, __LINE__, $sql);
        }
        while ( $row = $db->fetch_record($users_result) )
        {
            $user_online = ( !empty($row['session_id']) ) ? $user->lang['yes'] : $user->lang['no'];
            $user_active = ( $row['user_active'] == '1' ) ? $user->lang['yes'] : $user->lang['no'];
            
            $tpl->assign_block_vars('users_row', array(
                'ROW_CLASS' => $eqdkp->switch_row_class(),
                'U_MANAGE_USER' => 'manage_users.php'.$SID.'&amp;' . URI_NAME . '='.$row['username'],
                'NAME_STYLE' => ( $user->check_auth('a_', false, $row['user_id']) ) ? 'font-weight: bold' : 'font-weight: none',
                'USERNAME' => $row['username'],
                'U_MAIL_USER' => ( !empty($row['user_email']) ) ? 'mailto:'.$row['user_email'] : '',
                'EMAIL' => ( !empty($row['user_email']) ) ? $row['user_email'] : '&nbsp;',
                'LAST_VISIT' => date($user->style['date_time'], $row['user_lastvisit']),
                'ACTIVE' => $user_active,
                'ONLINE' => $user_online)
            );
        }
        
        $tpl->assign_vars(array(
            'L_MANAGE_USERS' => $user->lang['manage_users'],
            'L_USERNAME' => $user->lang['username'],
            'L_EMAIL' => $user->lang['email_address'],
            'L_LAST_VISIT' => $user->lang['last_visit'],
            'L_ACTIVE' => $user->lang['active'],
            'L_ONLINE' => $user->lang['online'],
            
            'O_USERNAME' => $current_order['uri'][0],
            'O_EMAIL' => $current_order['uri'][1],
            'O_LAST_VISIT' => $current_order['uri'][2],
            'O_ACTIVE' => $current_order['uri'][3],
            'O_ONLINE' => $current_order['uri'][4],
            
            'U_MANAGE_USERS' => 'manage_users.php'.$SID.'&amp;',
            
            'START' => $start,
            'LISTUSERS_FOOTCOUNT' => sprintf($user->lang['listusers_footcount'], $total_users, 100),
            'USER_PAGINATION' => generate_pagination('manage_users.php'.$SID.'&amp;o='.$current_order['uri']['current'], $total_users, 100, $start))
        );
        
        $page_title = sprintf($user->lang['title_prefix'], $eqdkp->config['guildtag'], $eqdkp->config['dkp_name']).': '.$user->lang['manage_users_title'];
        include_once($eqdkp_root_path . 'includes/page_header.php');
        
        $tpl->set_filenames(array(
            'body' => 'admin/listusers.html')
        );
        
        include_once($eqdkp_root_path . 'includes/page_tail.php');
        
        break;
}

/**
* Update or insert into auth_users table with new permission
* 
* @param $auth_id
* @param $auth_setting
* @return bool
*/
function update_auth_users($auth_id, $auth_setting = 'N', $check_query_type = true)
{
    global $db, $user_id;
    
    $upd_ins = ( $check_query_type ) ? switch_upd_ins($auth_id, $user_id) : 'upd';
    
    if ( (empty($auth_id)) || (empty($user_id)) )
    {
        return false;
    }
    
    if ( $upd_ins == 'upd' )
    {
        $sql = 'UPDATE ' . AUTH_USERS_TABLE . "
                SET auth_setting='".$auth_setting."'
                WHERE auth_id='".$auth_id."'
                AND user_id='".$user_id."'";
    }
    else
    {
        $sql = 'INSERT INTO ' . AUTH_USERS_TABLE . "
                (user_id, auth_id, auth_setting)
                VALUES ('".$user_id."','".$auth_id."','".$auth_setting."')";
    }
    
    if ( !($result = $db->query($sql)) )
    {
        return false;
    }
    return true;
}

function switch_upd_ins($auth_id, $user_id)
{
    global $db;
    
    $sql = 'SELECT o.auth_value
            FROM ' . AUTH_OPTIONS_TABLE . ' o, ' . AUTH_USERS_TABLE . " u
            WHERE (u.auth_id = o.auth_id)
            AND (u.user_id='".$user_id."')
            AND u.auth_id='".$auth_id."'";
    if ( $db->num_rows($db->query($sql)) > 0 )
    {
        return 'upd';
    }
    return 'ins';
}
?>